#include <stdlib.h>
#include <time.h>
#include "XrdDMSimFileCatalog.hh"
#include "XrdDMSimulator.hh"

XrdDMSimFileCatalog::XrdDMSimFileCatalog() :
    fMaxSites(0),
    fMaxFiles(0)
{
//   srand(time(0));
//   srand(1);
}

XrdDMSimFileCatalog::~XrdDMSimFileCatalog()
{

}

void XrdDMSimFileCatalog::Generate(XrdDMSimulator* sim, int numfiles, int filesPerSite)
{

  int numSites = sim->GetNumberOfSites();
  if (numSites>XRDDMSIM_MAX_SITES) {
    numSites = XRDDMSIM_MAX_SITES;
  }

  if (numfiles>XRDDMSIM_MAX_FILES) {
    numfiles = XRDDMSIM_MAX_FILES;
  }

  cout << "Generating " << numfiles << " files at " << numSites<< " sites ..."  << endl;

  char tmp[100];
  int num;
  for (int j=0;j<numfiles;j++)
    for (int i=0;i<filesPerSite;i++) {
      num = (int)(double)rand()/RAND_MAX*numSites;
      fSites[i][j].SetName(sim->GetSite(num)->GetName());
      fSites[i][j].SetSiteInfo(sim->GetSite(num)->GetSpeedMin(),sim->GetSite(num)->GetSpeedMax(),10);
      sprintf(tmp,"/dir/file%02d.root",j);
      fFiles[i][j].SetName(tmp);
      fIsFileStaged[i][j] = true;
    }

  //remove same files in same sites
  for (int j=0;j<numfiles;j++)
    for (int i=0;i<numSites;i++)
      for (int k=i+1;k<numSites;k++) {
//         cout << "Orig " << i << " "<< k << " "<< fSites[i][j].GetName() << "\t" << fSites[k][j].GetName() << endl;
        if (!fSites[i][j].GetName().compare(fSites[k][j].GetName())) {
          fSites[k][j].SetName("");
//         cout << "Removing " << fSites[i][j].GetName() << "\t" << fSites[k][j].GetName() << "=== "<< endl;
        }

      }

  fMaxFiles = numfiles;
  fMaxSites = numSites;
}


void XrdDMSimFileCatalog::SetNumberOfFilesNotStaged(string siteName)
{
  for (int j=0;j<fMaxFiles;j++)
    for (int i=0;i<fMaxSites;i++)
      if (!siteName.compare(fSites[i][j].GetName())) {
        fIsFileStaged[i][j] = false;
      }
}


void XrdDMSimFileCatalog::Print()
{
  for (int j=0;j<fMaxFiles;j++)
    for (int i=0;i<fMaxSites;i++) {
      if (!fFiles[i][j].GetName().empty())
        if (!fSites[i][j].GetName().empty())
          cout << "root://"<< fSites[i][j].GetName() << "/" << fFiles[i][j].GetName()<< endl;
    }
}


int XrdDMSimFileCatalog::GetFileIndex(string file)
{
//   cout << "We are searching file " <<file << endl;
  for (int j=0;j<fMaxFiles;j++) {
//     cout << "==" << fFiles[0][j].GetName()<< "==" << file<< "==" << endl;
    if (file.compare(fFiles[0][j].GetName()) == 0) {
//       cout << "Found "<< fFiles[0][j].GetName() << endl;
      return j;
    }
  }

  return -1;
}

int XrdDMSimFileCatalog::GetSiteIndex(string site,int index)
{
//   cout << "We are searching file " <<site << endl;

  for (int j=0;j<fMaxSites;j++) {
    cout << "==" << fSites[j][index].GetName()<< "==" << site<< "==" << endl;
    if (site.compare(fSites[j][index].GetName()) == 0) {
//         cout << "Found "<< fSites[j][index].GetName() << " with index " << j << endl;
      return j;
    }
  }

  return -1;
}



